package com.example.java;

/**
 * ClassName: Main
 * Package: com.example.java
 * Description:
 *
 * @Author 许启萌
 * @Create 2025/7/30 9:20
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        BankAccount b = new BankAccount();
        Thread t1 = new Thread(b);
        Thread t2 = new Thread(b);

        t1.run();
        t2.run();
    }
}

class BankAccount implements Runnable{
    Object obj = new Object();
    double balance = 3000.0 ;
    public void deposit(double amount){
        synchronized(obj){
            this.balance += amount ;
            System.out.println("存入："+amount+" ，当前余额："+this.balance);
        }
    }
    public void withdraw(double amount){
        synchronized (obj){
            if( this.balance - amount >= 0){
                this.balance -= amount ;
                System.out.println("取出："+amount+" ，当前余额："+this.balance);
            }else{
                System.out.println("余额不足，无法取出");

            }
        }
    }

    @Override
    public void run() {
        while(true){

            withdraw((double) (int)(Math.random()*1000.0+1));
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            deposit((double) (int)(Math.random()*1000.0+1));
        }
    }
}

